#!/bin/sh

#
#CHECK_PROC=serv                    #process name
CHECK_PROC=$1                       #process name
INTERVAL_SEC=5                      #seconds
COUNTER_MAXNUM=30                   #max times to reboot
SERVERBOOTLOG=/tmp/serverboot.log   #log file

COUNTER_CALL_PROC=0

echo 
echo $1 " ORACLE_HOME "  $ORACLE_HOME  >>$SERVERBOOTLOG
echo $1 " LD_LIBRARY_PATH "  $LD_LIBRARY_PATH >>$SERVERBOOTLOG

echo `date` " check_proc "$CHECK_PROC ", inter "$INTERVAL_SEC ", MAX "$COUNTER_MAXNUM "LogFile "$SERVERBOOTLOG  >> $SERVERBOOTLOG

#
ABSOLUTE_DIR=`dirname $0`
CURRENT_DIR=$PWD
cd /
if [ ! -e $0 ] ; then
  ABSOLUTE_DIR=$CURRENT_DIR/$ABSOLUTE_DIR
fi

ReStartProc()
{
    chmod +x $ABSOLUTE_DIR/$CHECK_PROC
    cd $ABSOLUTE_DIR
    echo  "restart proc " $CHECK_PROC"!!!" >>$SERVERBOOTLOG
    ./$CHECK_PROC >/dev/null 2>&1 &
}

while [ 1 ]
do

  PROC_IS_EXIST=0

  PROC_DIRS=`ls -d /proc/*`
  for CUR_DIR in $PROC_DIRS
  do
    CUR_NAME=$CUR_DIR"/cmdline"
    if [ -e $CUR_NAME ] ; then
      CUR_PROC=`cat $CUR_NAME`
      CUR_PROC_BASENAME=`basename $CUR_PROC 2>/dev/null`
      if [ $CUR_PROC_BASENAME ] ; then
        if [ $CHECK_PROC = $CUR_PROC_BASENAME ] ; then
          PROC_IS_EXIST=1
          break
        fi
      fi
    fi
  done

  if [ $PROC_IS_EXIST = 1 ]; then
    echo $CHECK_PROC" is existed"
    COUNTER_CALL_PROC=0
  else
    echo "no such process: "$CHECK_PROC

    COUNTER_CALL_PROC=`expr $COUNTER_CALL_PROC + 1`
    if [ $COUNTER_CALL_PROC -eq $COUNTER_MAXNUM ];
    then
      echo "#### reboot"
      echo `date` reboot >> $SERVERBOOTLOG
      sleep 1 
      #reboot 
    else
      echo `date` $CHECK_PROC restart >> $SERVERBOOTLOG
      ReStartProc
    fi

    echo "### \""$CHECK_PROC"\" restart "$COUNTER_CALL_PROC" times !"
  fi

  sleep $INTERVAL_SEC

done
